package com.golddaymicromall.activity.storemanager;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.AreaInfo;
import com.golddaymicromall.bean.CityInfo;
import com.golddaymicromall.bean.CountryInfo;
import com.golddaymicromall.bean.ProvinceInfo;
import com.golddaymicromall.bean.StoreDetailInfo;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.android.schedulers.AndroidSchedulers;

public class StoreUpdateActivity extends BaseActivity implements View.OnClickListener {

    //控件类
    private LinearLayout mStoreBack;
    private TextView mStoreNickName;
    private Spinner mStoreCountry;
    private Spinner mStoreProvince;
    private Spinner mStoreCity;
    private Spinner mStoreArea;
    private TextView mStoreQQ;
    private TextView mStoreEmail;
    private Button mStoreEdit;
    //参数类
    List<StoreDetailInfo> storeDetail;
    List<String> listCountry = null;
    List<ProvinceInfo> provinceInfo = null;
    List<CityInfo> cityInfo = null;
    List<AreaInfo> areaInfo = null;

    private String logid;
    private String nickName;
    private String countryId;
    private String provinceId;
    private String cityId;
    private String areaId;
    private String qq;
    private String email;
    private int provinceFlag = 1;
    private int cityFlag = 1;
    private int areaFlag = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_update);
        initView();
        //开始异步处理
        attemptStoreDetail();
        attemptGetCountryTask();
        attemptGetProvinceTask();
    }

    //获取店铺数据
    public void attemptStoreDetail() {
        logid = SPUtils.get(getApplicationContext(), "Id", "").toString();

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.customer.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", logid);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(StoreUpdateActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(StoreUpdateActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            //在这里进行返回值的处理
                            storeDetail = JSON.parseArray(result, StoreDetailInfo.class);
                            mStoreNickName.setText(storeDetail.get(0).getUsername());
                            mStoreEmail.setText(storeDetail.get(0).getEmail());
                            mStoreQQ.setText(storeDetail.get(0).getQq());
                        }
                    } else {
                        showError();
                        return;
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }

    public void attemptGetCountryTask() {

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getcountry");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(StoreUpdateActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(StoreUpdateActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            List<CountryInfo> result = JSON.parseArray(s, CountryInfo.class);
                            //在这里进行返回值的处理
                            listCountry = new ArrayList<String>();
                            for (int i = 0; i < result.size(); i++) {
                                listCountry.add(result.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(StoreUpdateActivity.this, android.R.layout.simple_spinner_dropdown_item, listCountry);
                            mStoreCountry.setAdapter(arrayAdapter);
                            mStoreCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < result.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(result.get(i).getName())) {
                                            countryId = result.get(i).getId();
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    } else {
                        showError();
                        return;
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    public void attemptGetProvinceTask() {

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getprovinces");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(StoreUpdateActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(StoreUpdateActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            provinceInfo = JSON.parseArray(s, ProvinceInfo.class);
                            final List<String> listProvince = new ArrayList<String>();
                            for (int i = 0; i < provinceInfo.size(); i++) {
                                listProvince.add(provinceInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(StoreUpdateActivity.this, android.R.layout.simple_spinner_dropdown_item, listProvince);
                            mStoreProvince.setAdapter(arrayAdapter);
                            if (provinceFlag == 1) {
                                for (int i = 0; i < provinceInfo.size(); i++) {
                                    if (provinceId != null && provinceId.equals(provinceInfo.get(i).getId())) {
                                        provinceFlag = 0;
                                        mStoreProvince.setSelection(i, true);
                                        attemptGetCityTask(provinceId);
                                    }
                                }
                            }
                            mStoreProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {

                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < provinceInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(provinceInfo.get(i).getName())) {
                                            provinceId = provinceInfo.get(i).getId();
                                            attemptGetCityTask(provinceId);
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    public void attemptStoreEditTask() {
        logid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        nickName = mStoreNickName.getText().toString().trim();
        qq = mStoreQQ.getText().toString().trim();
        email = mStoreEmail.getText().toString().trim();
        if (!isNumber(qq) || qq.length() > 10) {
            Toast.makeText(this, "qq不合法，请重新输入", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!"".equals(email) && !isEmial(email)) {
            Toast.makeText(this, "邮箱不合法，请重新输入", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.customer.update");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", logid);
        form.put("username", nickName);
        form.put("country", countryId);
        form.put("province", provinceId);
        form.put("city", cityId);
        form.put("area", areaId);
        form.put("email", email);
        form.put("qq", qq);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> showLoading())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    dismissLoading();

                    if (result.contains("errorToken")) {
                        Toast.makeText(StoreUpdateActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                    } else if (Integer.parseInt(result) == 1) {
                        Toast.makeText(StoreUpdateActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(StoreUpdateActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                    }

                }, throwable -> {
                    dismissLoading();
                    showError();
                    throwable.printStackTrace();
                });

    }

    public boolean isNumber(String Num) {
        Pattern p = Pattern
                .compile("^[0-9]*$");
        Matcher m = p.matcher(Num);
        return m.matches();
    }

    public boolean isEmial(String Num) {
        Pattern p = Pattern
                .compile("^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$");
        Matcher m = p.matcher(Num);
        return m.matches();
    }

    public void initView() {
        provinceId = getIntent().getStringExtra("provinceId");
        cityId = getIntent().getStringExtra("cityId");
        areaId = getIntent().getStringExtra("areaId");
        //控件
        mStoreBack = (LinearLayout) findViewById(R.id.store_back);
        mStoreNickName = (TextView) findViewById(R.id.storeNickName);
        mStoreCountry = (Spinner) findViewById(R.id.storeCountry);
        mStoreProvince = (Spinner) findViewById(R.id.storeProvince);
        mStoreCity = (Spinner) findViewById(R.id.storeCity);
        mStoreArea = (Spinner) findViewById(R.id.storeArea);
        mStoreQQ = (TextView) findViewById(R.id.storeQQ);
        mStoreEmail = (TextView) findViewById(R.id.storeEmail);
        mStoreQQ = (TextView) findViewById(R.id.storeQQ);
        mStoreEmail = (TextView) findViewById(R.id.storeEmail);
        mStoreEdit = (Button) findViewById(R.id.storeEdit);
        mStoreBack.setOnClickListener(this);
        mStoreEdit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.storeEdit:
                attemptStoreEditTask();
                MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                        SPUtils.get(getApplicationContext(), "Customerno", "").toString() + ",修改店铺类型");
                break;
            case R.id.store_back:
                finish();
                break;
        }
    }


    public void attemptGetCityTask(String provinceId) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getcity");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("province", provinceId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(StoreUpdateActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(StoreUpdateActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            cityInfo = JSON.parseArray(s, CityInfo.class);
                            if (cityInfo.size() != 0) {
                                final List<String> listCity = new ArrayList<String>();
                                for (int i = 0; i < cityInfo.size(); i++) {
                                    listCity.add(cityInfo.get(i).getName());
                                }
                                // adpater对象
                                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(StoreUpdateActivity.this, android.R.layout.simple_spinner_dropdown_item, listCity);
                                mStoreCity.setAdapter(arrayAdapter);
                                if (cityFlag == 1) {
                                    for (int i = 0; i < cityInfo.size(); i++) {
                                        if (cityId != null && cityId.equals(cityInfo.get(i).getId())) {
                                            cityFlag = 0;
                                            mStoreCity.setSelection(i, true);
                                            attemptGetAreaTask(cityId);
                                        }
                                    }
                                }
                                mStoreCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    @Override
                                    public void onItemSelected(AdapterView<?> parent, View view,
                                                               int position, long id) {
                                        Spinner spinner = (Spinner) parent;
                                        for (int i = 0; i < cityInfo.size(); i++) {
                                            if (spinner.getItemAtPosition(position).toString().equals(cityInfo.get(i).getName())) {
                                                cityId = cityInfo.get(i).getId();
                                                attemptGetAreaTask(cityId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> parent) {
                                        Toast.makeText(getApplicationContext(), "没有改变的处理",
                                                Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        }
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    public void attemptGetAreaTask(String cityId) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getdistrict");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("city", cityId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(StoreUpdateActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(StoreUpdateActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            areaInfo = JSON.parseArray(s, AreaInfo.class);

                            final List<String> listArea = new ArrayList<String>();
                            for (int i = 0; i < areaInfo.size(); i++) {
                                listArea.add(areaInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(StoreUpdateActivity.this, android.R.layout.simple_spinner_dropdown_item, listArea);
                            mStoreArea.setAdapter(arrayAdapter);
                            if (areaFlag == 1) {
                                for (int i = 0; i < areaInfo.size(); i++) {
                                    if (areaId != null && areaId.equals(areaInfo.get(i).getId())) {
                                        areaFlag = 0;
                                        mStoreArea.setSelection(i, true);
                                    }
                                }
                            }
                            mStoreArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < areaInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(areaInfo.get(i).getName())) {
                                            areaId = areaInfo.get(i).getId();
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
